package com.seek.inter;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.seek.authcheck.constants.AuthConstant;
import com.seek.cache.CacheUtil;
import com.seek.common.handler.SpringContextHolder;
import com.seek.constants.ApiParamsConstant;
import com.seek.constants.RedisCustomerConstant;
import com.seek.inter.interdto.InterDtoCUser;
import com.seek.model.dto.ResultInfo;
import com.seek.model.entity.TCustomerAddrbook;
import com.seek.service.CustomerAddrbookService;
import com.seek.service.CustomerService;
import com.seek.submail.utils.StringUtil;
import com.seek.util.CommonUtil;
import com.seek.util.RelationUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.transaction.annotation.Transactional;

/**
 * 通讯录相关接口
 * Created by weh on 2017/7/5.
 */
public class CustomerAddrbookInter {

  private CustomerAddrbookService customerAddrbookService = (CustomerAddrbookService) SpringContextHolder
      .getBean("customerAddrbookService");

  private CustomerService customerService = (CustomerService) SpringContextHolder
      .getBean("customerService");

  /**
   * 上传通讯录
   **/
  @Transactional
  public ResultInfo uploadAddrBook(HttpServletRequest request, JSONObject reqJson)
      throws Exception {
    ResultInfo result = new ResultInfo();
    String token = reqJson.getString(ApiParamsConstant.TOKEN);
    Long customerId = CommonUtil.getLongValue(reqJson.getString(ApiParamsConstant.CUST_ID));
    Long companyId = CommonUtil.getLongValue(reqJson.getString(ApiParamsConstant.COMPANY_ID));
    JSONArray addressArray = reqJson.getJSONArray(ApiParamsConstant.DATA);

    List<TCustomerAddrbook> books = new ArrayList<>();
    if (CollectionUtils.isNotEmpty(addressArray)) {
      for (int i = 0; i < addressArray.size(); i++) {
        JSONObject bookJson = addressArray.getJSONObject(i);
        TCustomerAddrbook book = new TCustomerAddrbook();
        String phoneNo = getPhone(bookJson.getString(ApiParamsConstant.PHONE_NO));
        //过滤无效手机号码
        if (StringUtils.isNotEmpty(phoneNo) && StringUtils.length(phoneNo) < 30) {
          book.setCompanyId(companyId);
          book.setCustomerId(customerId);
          book.setAddrType(2);
          book.setPhoneNo(phoneNo);
          String name = bookJson.getString(ApiParamsConstant.NAME);
          book.setPhoneName(name);
          String relation = RelationUtil.getRelation(name);
          book.setIsRealtive(StringUtils.isNotEmpty(relation) ? 1 : 0);
          book.setRelation(StringUtils.isNotEmpty(relation) ? relation : "朋友");
          books.add(book);
        }

      }
      // 删除历史上传记录
      customerAddrbookService
          .executeUpdate("delete from t_customer_addrbook where company_id = ? and customer_id= ? ",
              new Object[]{companyId, customerId});
      customerAddrbookService.saveBatch(books, customerId + "");

      customerService
          .executeUpdate("update t_customer set addrbook_status = ? where id = ?", 1, customerId);

      Map<String, Object> cacheData = new HashMap<>();
      cacheData.put(RedisCustomerConstant.ADDR_BOOK_STATUS, AuthConstant.AUTH_SUCCESS);
      CacheUtil.refreshCustRedis(token, cacheData);

    } else {
      result.setStatus(1);
      result.setMessage("通讯录为空！");
      return result;
    }
    result.setStatus(0);
    result.setMessage("操作成功");
    return result;
  }

  private String getPhone(String phone) {
    if (StringUtils.isEmpty(phone)) {
      return null;
    }
    try {
      phone = phone.replaceAll("\\D", "");
      if (phone.length() > 11 && phone.startsWith("86")) {
        phone = StringUtils.substring(phone, 2);
      }
      int phoneLen = StringUtils.length(phone);
      if (phoneLen > 12) {
        String reg = "^(13[0-9]|147|15[7-9]|153|156|17[0-9]|18[7-9])[0-9]{8}$";

        phone = StringUtils.substring(phone, phoneLen - 11);
        if (!phone.matches(reg)) {
          phone = "";
        }
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
    return phone;
  }

}
